package com.eco.fanliapp.job.messagepushjob;


import com.eco.fanliapp.dao.AppUserMapper;
import com.eco.fanliapp.service.JpushMessage;
import com.eco.fanliapp.utils.DateFormatUtils;
import com.eco.fanliapp.utils.EmojiUtil;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.List;

/**
 * 未签到提醒推送
 */
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class SignPushMessageTask implements Job, Serializable {


    private static final Logger log = LoggerFactory.getLogger(SignPushMessageTask.class);

    @Autowired
    private AppUserMapper appUserMapper;

    public SignPushMessageTask() {
    }

    @Override
    public void execute(JobExecutionContext context) {

        //取得job详情
        JobDetail jobDetail = context.getJobDetail();

        JobDataMap dataMap = jobDetail.getJobDataMap();

        int executeCount = 0;
        if (dataMap.containsKey("runCount")) {
            executeCount = dataMap.getInt("runCount");
        }

        // 增量计数并将其存储回 JobDataMap，这样可以适当保持工作状态
        executeCount++;
        dataMap.put("runCount", executeCount);

        long startTime = System.currentTimeMillis();
        log.info("***************************************开始执行未签到提醒推送任务-JobBusAdmire：executeCount=" + executeCount + "--startTime=" + startTime);

        String nowDate = DateFormatUtils.getCurrentDate();
        log.info("开始处理未签到提醒推送   0 30 19 * * ? ");

        try {

            //获取未签到用户
            List<String> appUserIdList = appUserMapper.selectNoSignUsers();
            //极光推送签到提醒

            String content = "别忘了来省鸭签到领现金哦～\n" +
                    "坚持天数越多，积累金额越大";
            String title = "签到提醒";

            if (CollectionUtils.isNotEmpty(appUserIdList)) {
                List<List<String>> subUserIdList = Lists.partition(appUserIdList, 1000);
                for (List<String> userIdlist : subUserIdList) {
                    JpushMessage.jiGuangPushMesageListAndroid(10001, EmojiUtil.resolveToEmojiFromByte(title), userIdlist, EmojiUtil.resolveToEmojiFromByte(content), 4001, null, null);
                    JpushMessage.jiGuangPushMesageListIos(10001, EmojiUtil.resolveToEmojiFromByte(title), userIdlist, EmojiUtil.resolveToEmojiFromByte(content), 4001, null, null);
                }
            }

        } catch (Exception e) {
            log.info("处理未签到提醒推送异常   0 30 19 * * ?");
        }
        log.info("结束处理未签到提醒推送   0 30 19 * * ?");
        long endTime = System.currentTimeMillis();
        log.info("***************************************结束执行未签到提醒推送任务-JobBusAdmire：executeCount=" + executeCount + "--endTime=" + endTime + "--耗时=" + (endTime - startTime));
    }
}
